package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementQuery;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 结算单接口
 */
@Service
@Transactional
public class StatementServiceImpl implements IStatementService {

    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private AppointmentMapper appointmentMapper;


    @Override
    public TablePageInfo<Statement> query(StatementQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<Statement>(statementMapper.selectForList(qo));
    }


    @Override
    public void save(Statement statement) {
        statement.setCreateTime(new Date());
        statementMapper.insert(statement);
    }

    @Override
    public Statement get(Long id) {
        return statementMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(Statement statement) {
        // 查询mysql数据
        Statement statement1 = this.get(statement.getId());
        // 判断状态必须为消费中
        if (!Statement.STATUS_CONSUME.equals(statement1.getStatus())){
            throw new  BusinessException("非法操作");
        }
        statementMapper.updateByPrimaryKey(statement);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            // 把数据查询出来,做判断判断
            Statement statement = this.get(dictId);
            // 删除结算单
            statementMapper.deleteByPrimaryKey(dictId);
            // 删除中间表数据
            statementMapper.deleteRelation(dictId);
            // 判断结算中预约单id 是否为空,如果不为空说明从预约单生成结算单
            // 需要把状态改回已到店状态,这样他就可以在此生成结算单了
            if (statement.getAppointmentId() != null){
                appointmentMapper.changeStatus(statement.getAppointmentId(), Appointment.STATUS_ARRIVAL);
            }

        }
    }

    @Override
    public List<Statement> list() {
        return statementMapper.selectAll();
    }



}












